package com.xuhuan.gulimall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuhuan.common.utils.PageUtils;
import com.xuhuan.common.utils.Query;

import com.xuhuan.gulimall.product.dao.CategoryDao;
import com.xuhuan.gulimall.product.entity.CategoryEntity;
import com.xuhuan.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询所有分类以及子分类，以树形结构组装起来
     *
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        // 1. 查出所有的分类
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);

        // 2. 组装成父子的树形结构
        // 2.1 找到所有的一级分类
        List<CategoryEntity> level1CategoryList = categoryEntityList.stream()
                .filter(c -> c.getParentCid() == 0)
                .map(c -> {
                    // 2.2 找到所有的一级分类的子分类
                    c.setChildren(getChildrens(c, categoryEntityList));
                    return c;
                })
                .sorted((c1, c2) -> {
                    return (c1.getSort() == null ? 0 : c1.getSort()) - (c2.getSort() == null ? 0 : c2.getSort());
                })
                .collect(Collectors.toList());
        return level1CategoryList;
    }

    /**
     * 批量删除
     *
     * @param catIdList
     */
    @Override
    public void removeMenuByIds(List<Long> catIdList) {
        // todo //检查当前删除的菜单是否被其他地方引用
        baseMapper.deleteBatchIds(catIdList);
    }

    /**
     * 获取分类的下级分类
     *
     * @param root
     * @param all
     * @return
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> childrens = all.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid().equals(root.getCatId()))
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildrens(categoryEntity, all));
                    return categoryEntity;
                })
                .sorted((c1, c2) -> {
                    return (c1.getSort() == null ? 0 : c1.getSort()) - (c2.getSort() == null ? 0 : c2.getSort());
                })
                .collect(Collectors.toList());
        return childrens;
    }


}